/*
 * Copyright (c) 2011 by Konstantin Pavlov.
 */

package gwtlx.html5.client.sql;

import com.google.gwt.core.client.JavaScriptObject;

/**
 * Web SQL Database wrapper implementation.
 *
 * @author Konstantin Pavlov
 * @version $LastChangedRevision: 20 $
 * @see <a href="http://dev.w3.org/html5/webdatabase/">Web SQL Database</a>
 * @since 30.05.2010
 */
public class Database extends JavaScriptObject {

    /** Prevents from creating instances */
    protected Database() {
    }

    /**
     * Casts javascript object to {@link Database}
     *
     * @param jso a javascript object to cast
     *
     * @return {@link Database} instance
     */
    private static Database as(JavaScriptObject jso) {
        return (Database) jso;
    }

    /**
     * Creates a database.
     *
     * @param dbName      database name
     * @param dbVersion   database version
     * @param displayName display name
     * @param sizeKb      estimated size in Kb.
     *
     * @return Reference to database or null if Web SQL Database API is not supported.
     */
    public static native Database openDatabase(String dbName, String dbVersion, String displayName, int sizeKb) /*-{
        if (!$wnd.openDatabase) {
            // Web SQL Database API is not supported by the browser
            return null;
        }
        try {
            var db = $wnd.openDatabase(dbName, dbVersion, displayName, sizeKb*1024,
                                      function (db) {
                                          db.changeVersion('', dbVersion);
                                      });
            return @gwtlx.html5.client.sql.Database::as(Lcom/google/gwt/core/client/JavaScriptObject;)(db);
        } catch (e) {
            alert("error=" + e);
            return null;
        }
    }-*/;

    public final native void transaction(String sql, Object... params)/*-{
        return this.transaction(function (t) {
            alert('started tx=' + t);
            t.executeSql(sql, params);
        })
    }-*/;

    public final native void readTransaction(String sql, Object... params)/*-{
        return this.readTransaction(function (t) {
            alert('started read tx=' + t);
            t.executeSql(sql, params)
        })
    }-*/;

    public final void createTable(String tableName, String... columns) {
        String sb = "CREATE TABLE " + tableName;
        boolean b = false;
        for (String column : columns) {
            if (b) {
                sb += ",";
            }
            sb += column;
            b = true;
        }
        transaction(sb);
    }

    /**
     * return the current version of the database
     *
     * @return return the current version of the database
     */
    public final native String getVersion() /*-{
        return this.version;
    }-*/;

    /**
     * returns database name
     *
     * @return return database name
     */
    public final native String getName() /*-{
        return this.name;
    }-*/;
}